package com.ytjj.qmyx.admin.service.impl;

import com.github.pagehelper.PageHelper;
import com.ytjj.common.api.CommonPage;
import com.ytjj.common.constants.CopyWriterConstant;
import com.ytjj.common.exception.ApiException;
import com.ytjj.common.utils.CopyWriterConfigUtil;
import com.ytjj.qmyx.admin.constants.SysConfigConstants;
import com.ytjj.qmyx.admin.dao.*;
import com.ytjj.qmyx.admin.model.request.*;
import com.ytjj.qmyx.admin.model.response.ProductActivityModelResponse;
import com.ytjj.qmyx.admin.model.response.ProductStockGroupResponse;
import com.ytjj.qmyx.admin.model.response.StockRemindResponse;
import com.ytjj.qmyx.admin.service.ProductActivityService;
import com.ytjj.qmyx.mall.mapper.*;
import com.ytjj.qmyx.mall.model.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class ProductActivityServiceImpl implements ProductActivityService {

    @Resource
    private ProductActivityDao productActivityDao;

    @Resource
    private ProductActivityMapper productActivityMapper;

    @Resource
    private ProductActivityImgMapper productActivityImgMapper;

    @Resource
    private ProductActivitySpecMapper productActivitySpecMapper;

    @Resource
    private ProductMapper productMapper;

    @Resource
    private ProductCategoryMapper productCategoryMapper;

    @Resource
    private BankerMapper bankerMapper;

    @Resource
    private ProductActivityMatchingMapper productActivityMatchingMapper;

    @Resource
    private ProductActivityMatchingDao productActivityMatchingDao;

    @Resource
    private ProductActivitySpecDao productActivitySpecDao;

    @Resource
    private ActivityColumnMapper activityColumnMapper;

    @Resource
    private CopyWriterConfigUtil copyWriterConfigUtil;

    @Resource
    private BrandDao brandDao;

    @Resource
    private ProductDao productDao;

    @Override
    public CommonPage<ProductActivityModelResponse> activityList(ActivityRequest activityRequest) {

        //一级分类
        if (!StringUtils.isEmpty(activityRequest.getCategoryTopTitle())) {
            ProductCategoryExample productCategoryExample = new ProductCategoryExample();
            productCategoryExample.createCriteria().andTitleEqualTo(activityRequest.getCategoryTopTitle());
            List<ProductCategory> list = productCategoryMapper.selectByExample(productCategoryExample);
            if (!CollectionUtils.isEmpty(list)) {
                ProductCategory pc = list.get(0);
                activityRequest.setPid(pc.getId());
            }
        }
        //二级分类
        if (!StringUtils.isEmpty(activityRequest.getCategoryTitle())) {
            ProductCategoryExample productCategoryExample = new ProductCategoryExample();
            productCategoryExample.createCriteria().andTitleEqualTo(activityRequest.getCategoryTitle());
            List<ProductCategory> list = productCategoryMapper.selectByExample(productCategoryExample);
            if (!CollectionUtils.isEmpty(list)) {
                ProductCategory pca = list.get(0);
                activityRequest.setPpid(pca.getId());
            }
        }

        PageHelper.startPage(activityRequest.getPageNum(), activityRequest.getPageSize());

        List<ProductActivityModelResponse> page = productActivityDao.activityList(activityRequest);
        if (!CollectionUtils.isEmpty(page)) {
            for (ProductActivityModelResponse productActivityModelResponse : page) {
                Product product = productMapper.selectByPrimaryKey(productActivityModelResponse.getProductId());
                //根据categoryId拿到的是二级分类信息
                ProductCategory productCategory = productCategoryMapper.selectByPrimaryKey(product.getCategoryId());
                //获取一级分类信息
                ProductCategory pcTop = productCategoryMapper.selectByPrimaryKey(productCategory.getPid());
                Banker banker = bankerMapper.selectByPrimaryKey(product.getBankerId());
                ActivityColumn activityColumn = activityColumnMapper.selectByPrimaryKey(productActivityModelResponse.getColumnId());
                //商品二级名称
                productActivityModelResponse.setCategoryTitle(productCategory.getTitle());
                //商品一级名称
                productActivityModelResponse.setCategoryTopTitle(pcTop.getTitle());
                productActivityModelResponse.setBankerName(banker.getName());
                if (null != activityColumn) {
                    productActivityModelResponse.setColumnTitle(activityColumn.getTitle());
                }
                //品牌名称
                if (productActivityModelResponse.getBrandId() != null) {
                    productActivityModelResponse.setBrandName(brandDao.getBrandName(productActivityModelResponse.getBrandId()));
                }
            }
        }
        return CommonPage.restPage(page);
    }

    @Override
    public int updateActivity(ProductActivity productActivity) {
        productActivity.setUpdateTime(new Date());
        return productActivityMapper.updateByPrimaryKey(productActivity);
    }

    @Override
    public int updateActivityStatus(Integer id) {
        ProductActivity productActivity = productActivityMapper.selectByPrimaryKey(id);
        if (productActivity.getStatus() == SysConfigConstants.Activity_Status.STATUS_1) {
            productActivity.setStatus(SysConfigConstants.Activity_Status.STATUS_2);
            //改为下架状态后 商品管理中该商品is_hide改为显示
            productDao.updateIsHide(productActivity.getProductId(), 0);
        } else if (productActivity.getStatus() == SysConfigConstants.Activity_Status.STATUS_2) {
            productActivity.setStatus(SysConfigConstants.Activity_Status.STATUS_1);
            //活动商品在添加活动时默认下架状态，改为上架状态后 商品管理中该商品is_hide改为隐藏
            productDao.updateIsHide(productActivity.getProductId(), 1);
        }
        productActivity.setUpdateTime(new Date());
        return productActivityMapper.updateByPrimaryKeySelective(productActivity);
    }

    @Override
    public CommonPage<ProductActivitySpec> getActivitySpecsById(ActivitySpectRequest activitySpectRequest) {
        PageHelper.startPage(activitySpectRequest.getPageNum(), activitySpectRequest.getPageSize());
        List<ProductActivitySpec> productActivitySpecs = productActivityDao.getActivitySpecsById(activitySpectRequest);
        return CommonPage.restPage(productActivitySpecs);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateActivitySpec(ProductActivitySpec productActivitySpec) {
        productActivitySpec.setUpdateTime(new Date());
        int count = productActivitySpecMapper.updateByPrimaryKeySelective(productActivitySpec);
        // 重新计算总库存 set 总库存
        Integer stockSum = productActivitySpecDao.queryStockSum(productActivitySpec.getActivityId());
        if (stockSum == null) {
            throw new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.NO_SPECIFICATION));
        }
        ProductActivity productActivity = new ProductActivity();
        productActivity.setId(productActivitySpec.getActivityId());
        productActivity.setStock(stockSum);
        productActivityMapper.updateByPrimaryKeySelective(productActivity);
        return count;
    }

    @Override
    public CommonPage<ProductActivityImg> getActivityImgsById(ActivityImgRequest activityImgRequest) {
        PageHelper.startPage(activityImgRequest.getPageNum(), activityImgRequest.getPageSize());
        List<ProductActivityImg> productActivityImgs = productActivityDao.getActivityImgsById(activityImgRequest);
        return CommonPage.restPage(productActivityImgs);
    }

    @Override
    public int addActivityImg(ProductActivityImgRequest productActivityImgRequest) {
        int count = 0;

        if (productActivityImgRequest.getProductId() == null) {
            throw new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.PRODUCT_ID_NOT_NULL));
        }
        if (!CollectionUtils.isEmpty(productActivityImgRequest.getImgUrls())) {
            for (Map<String, String> param : productActivityImgRequest.getImgUrls()) {
                String name = param.get("name").substring(0, param.get("name").indexOf("."));
                Integer num = 0;
                if (productActivityImgRequest.getFileType().equals("img") && !name.equals("0")) {
                    try {
                        num = Integer.parseInt(name);
                    } catch (RuntimeException e) {
                        throw new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.FILE_NAME_MUST_NUMBER));
                    }
                } else {
                    num = 1;
                }
                ProductActivityImg productActivityImg = new ProductActivityImg();
                productActivityImg.setImgUrl(param.get("url"));
                productActivityImg.setProductId(productActivityImgRequest.getProductId());
                productActivityImg.setSort(num);
                productActivityImg.setType(productActivityImgRequest.getType());
                productActivityImg.setFileType(productActivityImgRequest.getFileType());
                productActivityImg.setCreateTime(new Date());
                count = productActivityImgMapper.insert(productActivityImg);
            }
        } else {
            throw new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.FILE_NOT_NULL));
        }
        //同步商品活动是否存在推荐recImgFlag
        if (productActivityDao.isRecImgFlag(productActivityImgRequest.getProductId()) > 0) {
            productActivityDao.updateRecImgFlag(productActivityImgRequest.getProductId(), 1);
        } else {
            productActivityDao.updateRecImgFlag(productActivityImgRequest.getProductId(), 0);
        }
        return count;
    }

    @Override
    public int updateActivityImg(ProductActivityImg productActivityImg) {
        //同步商品活动是否存在推荐recImgFlag
        if (productActivityDao.isRecImgFlag(productActivityImg.getProductId()) > 0) {
            productActivityDao.updateRecImgFlag(productActivityImg.getProductId(), 1);
        } else {
            productActivityDao.updateRecImgFlag(productActivityImg.getProductId(), 0);
        }
        productActivityImg.setUpdateTime(new Date());
        return productActivityImgMapper.updateByPrimaryKeySelective(productActivityImg);
    }

    @Override
    public void deleteActivityImg(Integer id) {
        ProductActivity productActivity = productActivityDao.getProductActivityById(productActivityDao.getProductActivityImg(id));
        if (productActivityDao.isRecImgFlag(productActivity.getProductId()) > 0) {
            productActivityDao.updateRecImgFlag(productActivity.getProductId(), 1);
        } else {
            productActivityDao.updateRecImgFlag(productActivity.getProductId(), 0);
        }
        productActivityImgMapper.deleteByPrimaryKey(id);
    }

    @Override
    public ProductActivityMatching getProductActivityMatching(Integer productId) {
        ProductActivityMatchingExample productActivityMatchingExample = new ProductActivityMatchingExample();
        productActivityMatchingExample.createCriteria().andProductIdEqualTo(productId);
        List<ProductActivityMatching> productActivityMatchings = productActivityMatchingMapper.selectByExampleWithBLOBs(productActivityMatchingExample);
        if (!CollectionUtils.isEmpty(productActivityMatchings)) {
            return productActivityMatchings.get(0);
        }
        return null;
    }

    @Override
    public int updateProductActivityMatching(ProductActivityMatching productActivityMatching) {
        // 修改或增加时，需要先判断是否存在改推荐信息记录
        ProductActivityMatchingExample productActivityMatchingExample = new ProductActivityMatchingExample();
        productActivityMatchingExample.createCriteria()
                .andProductIdEqualTo(productActivityMatching.getProductId());
        List<ProductActivityMatching> list = productActivityMatchingMapper.selectByExampleWithBLOBs(productActivityMatchingExample);
        if (!CollectionUtils.isEmpty(list)) {
            ProductActivityMatching pam = list.get(0);
            productActivityMatching.setUpdateTime(new Date());
            return productActivityMatchingDao.updateProductActivityMatchingByProduct(productActivityMatching);
        }
        productActivityMatching.setCreateTime(new Date());
        return productActivityMatchingDao.insertProductActivityMatching(productActivityMatching);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateStockBatch(Integer stock) {
        // 修改所有商品的规格库存
        productActivitySpecDao.updateSpecStocks(stock);
        // 根据商品id分组 进行库存计总
        List<ProductStockGroupResponse> list = productActivityDao.productStockGroup();
        if (!CollectionUtils.isEmpty(list)) {
            for (ProductStockGroupResponse data : list) {
                productActivityDao.updateStock(data.getProductId(), data.getStockSum());
            }
        }
        return list.size();
    }

    @Override
    public int updatePriceStock(Integer productId, BigDecimal price, Integer stock) {
        return productActivityDao.updatePriceStock(productId, price, stock);
    }

    @Override
    public int updateStock(Integer productId, Integer stockSum) {
        return productActivityDao.updateStock(productId, stockSum);
    }

    @Override
    public Integer delProductActivity(Integer id) {
        return productActivityDao.delProductActivity(id);
    }

    @Override
    public CommonPage<StockRemindResponse> getStockInfo(StockRemindRequest stockRemindRequest) {
        PageHelper.startPage(stockRemindRequest.getPageNum(), stockRemindRequest.getPageSize());
        List<StockRemindResponse> pageList = productActivityDao.getStockInfo(stockRemindRequest.getStockNum());
        return CommonPage.restPage(pageList);
    }

    @Override
    public Integer syncSpecInfo() {
        List<ProductActivityModelResponse> pageList = productActivityDao.syncList();
        Integer count = 0;
        if(!CollectionUtils.isEmpty(pageList)) {
            for(ProductActivityModelResponse pam : pageList) {
                count = productActivityDao.syncSpec(pam.getId(), pam.getCurPrice());
            }
        }
        return count;
    }
}
